﻿/**
 * @file DataCenter.cpp
 * @author monster
 * @date 2024/4/5
 */

/*********************
 *      INCLUDES
 *********************/
#include "DataCenter.h"

#include <string.h>
#include<algorithm>

/**********************
 *      MACROS
 **********************/


DataCenter::DataCenter(const char *id) :
        AccountMain(id, this) {
    ID = id;
}

DataCenter::~DataCenter() {

//    while (!AccountPool.empty()) {
//        Account *account = AccountPool.back();
//
//        delete account;
//        AccountPool.pop_back();
//    }

}


/**
 * @brief Add an account to the account pool
 * @param account Pointer to account
 * @return 0: account addition successful; !0: failed
*/
bool DataCenter::AddAccount(Account *account) {
    if (account == &AccountMain) {
        return false;
    }

    if (SearchAccount(account->ID) != nullptr) {
        DC_LOG_WARN("Multi add account: \"%s\"", account->ID);
        return false;
    }

    AccountPool.push_back(account);

    return true;
}

bool DataCenter::RemoveAccount(Account *account) {
    return Remove(&AccountPool, account);
}

bool DataCenter::Remove(Account::AccountVector_t *vec, Account *account) {
    auto iter = std::find(vec->begin(), vec->end(), account);

    if (iter == vec->end()) {
        DC_LOG_WARN("Account: '%s' was not found", account->ID);
        return false;
    }

    vec->erase(iter);
    return true;
}

Account *DataCenter::SearchAccount(const char *id) {
    return Find(&AccountPool, id);
}

/**
 * @brief Find account in vector
 * @param vec Pointer to vector
 * @param id Account ID
 * @return If the search is successful, return the pointer of the account
*/
Account *DataCenter::Find(Account::AccountVector_t *vec, const char *id) {
    for (auto iter: *vec) {
        if (strcmp(id, iter->ID) == 0) {
            return iter;
        }
    }
    return nullptr;
}
